package com.hethongviet.vending.helper.call;

import java.lang.reflect.Method;

import com.hethongviet.vending.AppMain;
import com.hethongviet.vending.Utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import com.android.internal.telephony.ITelephony;

public class IncomingCallReceiver extends BroadcastReceiver
{
	private OnIncomingCall onIncomingCall = null;

	private static IncomingCallReceiver instance = null;

	public IncomingCallReceiver()
	{
		super();
	}

	public synchronized static IncomingCallReceiver getInstance()
	{
		if (instance == null)
		{
			instance = new IncomingCallReceiver();
		}

		return instance;
	}

	@Override
	public void onReceive(Context context, Intent data)
	{
		/*
		 * End any call - but it is more delay than using service and it can
		 * recognize even if the app stop
		 */
		try
		{
			TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			Class<?> managerClass = Class.forName(manager.getClass().getName());
			Method methodGetITelephony = managerClass.getDeclaredMethod("getITelephony");
			methodGetITelephony.setAccessible(true);
			ITelephony telephony = (ITelephony) methodGetITelephony.invoke(manager);
			telephony.endCall();

			return;
		} catch (Exception e)
		{
			e.printStackTrace();
		}

		if (!AppMain.getInstance().isContextRunning("com.hethongviet.vending.pages.StandbyActivity"))
		{
			Utils.debug("The stand screen is not running!!!!");
			return;
		}

		Bundle bundle = data.getExtras();
		if (bundle == null)
		{
			return;
		}

		if (bundle.getString(TelephonyManager.EXTRA_STATE).equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING))
		{
			String cellPhoneIncom = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
			Utils.debug("incoming number: " + cellPhoneIncom);

			if (cellPhoneIncom != null && onIncomingCall != null)
				onIncomingCall.onIncomingCall(cellPhoneIncom.trim());
		}
	}

	public OnIncomingCall getOnIncomingCall()
	{
		return onIncomingCall;
	}

	public void setOnIncomingCall(OnIncomingCall onIncomingCall)
	{
		this.onIncomingCall = onIncomingCall;
	}

}
